package com.estore.network;

import com.com.estore02.model.Product;
import com.com.estore02.service.ProductService;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 商城服务器 - 处理所有客户端请求
 */
public class EStoreServer {
    private final ProductService productService;
    private final int port;
    private final ExecutorService threadPool;
    private volatile boolean running;

    public EStoreServer(int port) {
        this.port = port;
        this.productService = new ProductService();
        this.threadPool = Executors.newFixedThreadPool(10); // 线程池处理并发
        this.running = true;
    }

    /**
     * 启动服务器
     */
    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("🖥️  商城服务器已启动，监听端口: " + port);
            System.out.println("📊 初始商品数量: " + productService.getAllProducts().size());

            while (running) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("🔗 客户端连接: " + clientSocket.getInetAddress());

                    // 为每个客户端创建独立线程处理
                    threadPool.execute(() -> handleClient(clientSocket));

                } catch (IOException e) {
                    if (running) {
                        System.out.println("❌ 接受客户端连接失败: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("❌ 服务器启动失败: " + e.getMessage());
        } finally {
            threadPool.shutdown();
            System.out.println("🛑 服务器已关闭");
        }
    }

    /**
     * 处理客户端请求
     */
    private void handleClient(Socket clientSocket) {
        String clientInfo = clientSocket.getInetAddress().toString();

        try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

            output.flush(); // 刷新头信息

            while (running && !clientSocket.isClosed()) {
                try {
                    // 读取客户端请求
                    String request = (String) input.readObject();
                    System.out.println("📨 收到请求 [" + clientInfo + "]: " + request);

                    // 处理请求并返回响应
                    Object response = processRequest(request);
                    output.writeObject(response);
                    output.flush();

                    System.out.println("📤 发送响应 [" + clientInfo + "]: " +
                            (response instanceof List ? "商品列表(" + ((List<?>)response).size() + "项)" : response));

                } catch (EOFException e) {
                    // 客户端正常关闭连接
                    break;
                } catch (ClassNotFoundException e) {
                    System.out.println("❌ 无效的请求格式: " + e.getMessage());
                    output.writeObject("ERROR: 无效的请求格式");
                    output.flush();
                }
            }

        } catch (IOException e) {
            System.out.println("❌ 客户端处理错误 [" + clientInfo + "]: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
                System.out.println("🔌 客户端断开连接: " + clientInfo);
            } catch (IOException e) {
                // 忽略关闭异常
            }
        }
    }

    /**
     * 处理具体业务请求
     */
    private Object processRequest(String request) {
        try {
            switch (request) {
                case "GET_ALL_PRODUCTS":
                    return productService.getAllProducts();

                case "GET_AVAILABLE_PRODUCTS":
                    return productService.getAvailableProducts();

                case "GET_PRODUCT_COUNT":
                    return productService.getTotalProductCount();

                case "SEARCH_PRODUCTS":
                    // 这里需要更多参数，暂时返回所有商品
                    return productService.getAllProducts();

                case "CHECK_STOCK":
                    return "STOCK_CHECK_NEEDS_ID";

                case "SHUTDOWN":
                    if (running) {
                        running = false;
                        return "SERVER_SHUTTING_DOWN";
                    }
                    return "SERVER_ALREADY_SHUTDOWN";

                default:
                    if (request.startsWith("GET_PRODUCT:")) {
                        String productId = request.substring(12);
                        Product product = productService.findProductById(productId);
                        return product != null ? product : "PRODUCT_NOT_FOUND";
                    }
                    return "UNKNOWN_COMMAND: " + request;
            }
        } catch (Exception e) {
            return "ERROR: " + e.getMessage();
        }
    }

    /**
     * 停止服务器
     */
    public void stop() {
        running = false;
        threadPool.shutdown();
    }

    public static void main(String[] args) {
        int port = 8888;
        if (args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.out.println("⚠️  无效端口号，使用默认端口: 8888");
            }
        }

        EStoreServer server = new EStoreServer(port);

        // 添加关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n🛑 正在关闭服务器...");
            server.stop();
        }));

        server.start();
    }
}